﻿using InstanceGenerator;
using InternetSpiderLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace VerticalSpider.Core
{
    /// <summary>
    /// 蜘蛛的启动器
    /// </summary>
    public class SpiderStarter
    {
        /// <summary>
        /// 描述文件
        /// </summary>
        public string DescriptionFile { get; set; }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            var spiders = CreateNetSpider();
            if (spiders != null && spiders.Any())
            {
                foreach (var item in spiders)
                    item.Run();
            }
        }

        /// <summary>
        /// 创建场景对象
        /// </summary>
        /// <returns></returns>
        internal List<NetSpider> CreateNetSpider()
        {
            List<NetSpider> spiders = new List<NetSpider>();

            using (StreamReader fs = new StreamReader(DescriptionFile, Encoding.UTF8))
            {
                XmlDocument document = new XmlDocument();
                document.LoadXml(fs.ReadToEnd());

                var items = XmlInstanceGenerator.Generator(document);

                foreach (var item in items)
                {
                    if (typeof(NetSpider).IsAssignableFrom(item.GetType()))
                    {
                        spiders.Add((NetSpider)item);
                    }
                }
            }

            return spiders;
        }
    }
}
